﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class LAOSalvagePayments : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
            
        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            //try
            //{
            //    var bc = new UserComponent();
            //    var user = ReadUser();
            //    user.MustChangePassword = true;
            //    user.UserID = bc.Create(user);
            //    var audit = new FrameworkManapro.Audit.Audit<User>
            //    {
            //        EntityKey = user.UserID.ToString(),
            //        EventDate = DateTime.Now,
            //        EventType = FrameworkManapro.Audit.AuditEvent.Insert,
            //        NewObject = user,
            //        UserId = ((User)Session["User"]).UserID
            //    };
            //    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
            //    auditDAC.InsertAudit();
            //    wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully saved.", null);
            //    popupExtenderMessage.Show();
            //    this.PagingControl.TotalRecords = Search();
            //    Search();
            //    ClearFields();
            //}
            //catch (Exception ex)
            //{
            //    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New user", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
            //    wucMessage.ShowMessage(UserControls.MessageType.Error, "The user could not be saved", null);
            //    popupExtenderMessage.Show();
            //}
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            //btnSave.Visible = false;
            //btnNew.Visible = true;
            //var bc = new UserComponent();
            //try
            //{
            //    var user = ReadUser();
            //    if (hfUserId.Value.Trim() != string.Empty)
            //    {
            //        user.UserID = int.Parse(hfUserId.Value);
            //        var oldUser = bc.GetDetails(user.UserID);
            //        bc.Edit(user);
            //        var audit = new FrameworkManapro.Audit.Audit<User>
            //        {
            //            EntityKey = user.UserID.ToString(),
            //            EventDate = DateTime.Now,
            //            EventType = FrameworkManapro.Audit.AuditEvent.Update,
            //            OldObject = oldUser,
            //            NewObject = user,
            //            UserId = ((User)Session["User"]).UserID
            //        };
            //        var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
            //        auditDAC.InsertAudit();
            //        wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully saved.", null);
            //        popupExtenderMessage.Show();
            //        Search();
            //        ClearFields();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save user", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
            //    wucMessage.ShowMessage(UserControls.MessageType.Error, "The user couldn't be saved.", null);
            //    popupExtenderMessage.Show();
            //}
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            //if (grvUsers != null)
            //{
            //    if (grvUsers.SelectedDataKey != null)
            //    {
            //        try
            //        {
            //            var userId = (int)this.grvUsers.SelectedDataKey.Value;
            //            var bc = new UserComponent();
            //            var user = bc.GetDetails(userId);
            //            hfUserId.Value = userId.ToString();
            //            txtIdentity.Text = user.IdentificationNumber.ToString();
            //            txtFirstName.Text = user.Name;
            //            txtLastName.Text = user.LastName;
            //            txtDepartment.Text = user.Department;
            //            txtDescription.Text = user.Description;
            //            txtEmail.Text = user.Email;
            //            txtLogin.Text = user.Login;
            //            var hdRoleId = grvUsers.SelectedRow.FindControl("hdRoleId") as HiddenField;
            //            if (hdRoleId != null) ddlRole.SelectedValue = hdRoleId.Value;
            //            optOptions.SelectedValue = user.Status.ToString();
            //            btnSave.Visible = true;
            //            btnNew.Visible = false;
            //        }
            //        catch (Exception ex)
            //        {
            //            FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify user", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
            //            wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the user.", ex.ToString());
            //            popupExtenderMessage.Show();
            //        }
            //    }
            //    else
            //    {
            //        wucMessage.ShowMessage(UserControls.MessageType.Information, "A user must be selected.", null);
            //        popupExtenderMessage.Show();
            //    }
            //}
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            //if (grvUsers.SelectedDataKey != null)
            //{
            //    popupExtenderConfirm.Show();
            //}
            //else
            //{
            //    wucMessage.ShowMessage(UserControls.MessageType.Information, "A user must be selected.", null);
            //    popupExtenderMessage.Show();
            //}
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            //try
            //{
            //    var bc = new UserComponent();
            //    if (grvUsers.SelectedDataKey != null)
            //    {
            //        var userId = (int)this.grvUsers.SelectedDataKey.Value;
            //        var user = new User { UserID = userId, Role = new Role() };
            //        if (grvUsers != null)
            //        {
            //            var hdRoleId = grvUsers.SelectedRow.FindControl("hdRoleId") as HiddenField;
            //            if (hdRoleId != null) user.Role.RoleID = int.Parse(hdRoleId.Value);
            //        }
            //        var oldUser = bc.GetDetails(user.UserID);
            //        bc.Delete(user);
            //        var audit = new FrameworkManapro.Audit.Audit<User>
            //        {
            //            EntityKey = user.UserID.ToString(),
            //            EventDate = DateTime.Now,
            //            EventType = FrameworkManapro.Audit.AuditEvent.Delete,
            //            OldObject = oldUser,
            //            UserId = ((User)Session["User"]).UserID
            //        };
            //        var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<User>(audit);
            //        auditDAC.InsertAudit();
            //        this.PagingControl.TotalRecords = Search();
            //        Search();
            //        wucMessage.ShowMessage(UserControls.MessageType.Success, "The user was successfully deleted.", null);
            //        popupExtenderMessage.Show();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete user", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
            //    wucMessage.ShowMessage(UserControls.MessageType.Error, "The user couldn't be deleted.", ex.ToString());
            //    popupExtenderMessage.Show();
            //}
            
        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            } 
            ClearFields();
        }
        
        #endregion

        #region Other Events

        protected void grvLAOSalvagePayments_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvLAOSalvagePayments, "Select$" + e.Row.RowIndex);
                
            }
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            //txtCheckNumber.Text = string.Empty;
            //txtName.Text = string.Empty;
            //txtCheckNumberSearch.Text = string.Empty;
            //txtNameSeach.Text = string.Empty;
            //optOptions.SelectedValue = "True";
            //hfID.Value = string.Empty;

        }
        private void Initialize()
        {
            try
            {
                foreach (int i in Enum.GetValues(typeof(GeneralEnumTypes.StatusLAOSalvagePayments)))
                {
                    this.ddlStatus.Items.Add(new ListItem(Enum.GetName(typeof(GeneralEnumTypes.StatusLAOSalvagePayments), i).ToString().Replace('_', ' '), i.ToString()));
                    //this.ddlYearOfSettlementSearch.Items.Add(new ListItem(Enum.GetName(typeof(GeneralEnumTypes.YearOfSettlement), i).ToString().Replace('_', ' '), i.ToString()));
                }
                this.ddlStatus.Items.Insert(0, new ListItem("Select...", String.Empty));

                this.ddlAccountNumber.Items.Add( new ListItem("70100008005777","70100008005777"));
                this.ddlAccountNumber.Items.Add( new ListItem("70100008005777","70100008005777"));
                this.ddlAccountNumber.Items.Insert(0, new ListItem("Select...", String.Empty));

                this.ddlAccountNumberSearch.Items.Add(new ListItem("70100008005777", "70100008005777"));
                this.ddlAccountNumberSearch.Items.Add(new ListItem("70100008005777", "70100008005777"));
                this.ddlAccountNumberSearch.Items.Insert(0, new ListItem("Select...", String.Empty));
                //this.ddlYearOfSettlementSearch.Items.Insert(0, new ListItem("Select...", String.Empty));
 
                btnSave.Visible = false;
                btnNew.Visible = true;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected Historic Repurchases?", null);
                this.PagingControl.TotalRecords = Search();
				Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        private void ValidateSecurity()
        {
            //var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("User");
            //if (beEntities == null) return;
            //if (!beEntities.CanRead)
            //{
            //    grvUsers.Visible = false;
            //    btnModify.Visible = false;
            //    btnDelete.Visible = false;
            //    pnlSearch.Visible = false;
            //}
            //if (!beEntities.CanWrite)
            //{
            //    btnSave.Visible = false;
            //}
            //if (!beEntities.CanInsert)
            //{
            //    btnNew.Visible = false;
            //    btnCancel.Visible = false;
            //    pnlEdit.Visible = false;
            //}
            //if (!beEntities.CanDelete)
            //{
            //    btnDelete.Visible = false;
            //}
        }
        private int Search()
        {
            //try
            //{
            //    var bc = new UserComponent();
            //    var userName = txtNameSeach.Text;
            //    var login = txtLoginSearch.Text;
            //    int? roleId = null;
            //    int? identificationNumber = null;
            //    if (!string.IsNullOrEmpty(ddlRoleSearch.SelectedValue))
            //        roleId = int.Parse(ddlRoleSearch.SelectedValue);
            //    if (!string.IsNullOrEmpty(txtIdentitySearch.Text))
            //        identificationNumber = int.Parse(txtIdentitySearch.Text);
            //    FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
            //    paging.PageNumber = this.PagingControl.PageNumber;
            //    paging.PageSize = this.PagingControl.PageSize;
            //    paging.SortBy = this.PagingControl.SortExpression;
            //    paging.SortDirection = this.PagingControl.SortDirection;


            //    UserCollection Usercollection = bc.Search(userName, roleId, identificationNumber, login, paging);                 

            //    grvUsers.DataSource = Usercollection;
            //    grvUsers.DataBind();
            //    return Usercollection.TotalResults;
            //}
            //catch (Exception ex)
            //{
            //    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search user", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
            //    wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
            //    popupExtenderMessage.Show();
            grvLAOSalvagePayments.DataSource = GenerateDataTablePrueba();
            grvLAOSalvagePayments.DataBind();
               return 1;
            //}
        }
        //private User ReadUser()
        //{
        //    var user = new User
        //    {
        //        IdentificationNumber = int.Parse(txtIdentity.Text),
        //        Name = txtFirstName.Text,
        //        LastName = txtLastName.Text,
        //        Department = txtDepartment.Text,
        //        Description = txtDescription.Text,
        //        Email = txtEmail.Text,
        //        Login = txtLogin.Text,
        //        Password = System.Configuration.ConfigurationManager.AppSettings["defaultPassword"],
        //        Status = bool.Parse(optOptions.SelectedValue),
        //        Role = new Role { RoleID = int.Parse(ddlRole.SelectedValue) },
        //    };
        //    return user;
        //}
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
             Search();
        }
        #endregion

        private DataTable GenerateDataTablePrueba()
        {
            //            •	ACCOUNTNUMBER:  Número de cuenta
            //•	PAYMENTREASONCODE: estatus
            //•	POSTGENERALLEDGERDATE: Fecha del pago
            //•	PAIDPRINCIPALAMOUNT: Capital
            //•	PAIDINTERESTAMOUNT: Interese Devengados
            //•	TOTALAMOUNT: MontoTotal

            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("AccountNumber", typeof(string));
            dt.Columns.Add("PaymentReasonCode", typeof(string));
            dt.Columns.Add("PostGeneralledgerDate", typeof(string));
            dt.Columns.Add("PaidPrincipalAmount", typeof(string));
            dt.Columns.Add("PaidInterestAmount", typeof(string));
            dt.Columns.Add("TotalAmount", typeof(string));
            DataRow rowdt;
            rowdt = dt.NewRow();
            rowdt[0] = "1";
            rowdt[1] = "70100004107866";
            rowdt[2] = "Pago";
            rowdt[3] = "6/4/2008";
            rowdt[4] = "1,523.51";
            rowdt[5] = "215.45";
            rowdt[6] = "1,738.96";

            dt.Rows.Add(rowdt);
            
            return dt;

        }

    }
}
